using System;
using WindowServices.Server.Interface;

namespace WindowServices.Service.Command.Task
{
    internal abstract class TaskBase : ITask
    {
        private readonly ServiceEntityEx _se;
        protected TaskBase(ServiceEntityEx se)
            : this(se, 0)
        {
            _se = se;
            State = TaskState.None;
        }
        protected TaskBase(ServiceEntityEx se, int order)
        {
            _se = se;
            State = TaskState.None;
            Order = order;
        }

        public TaskState State
        {
            get;
            private set;
        }

        public void Execute()
        {
            if (State != TaskState.None)
            {
                return;
            }

            try
            {
                Execute(_se);
            }
            catch (Exception)
            {
                State = TaskState.Error;
                throw;
            }
            State = TaskState.Success;
        }

        public void RollBack()
        {
            if (State == TaskState.None)
            {
                return;
            }

            try
            {
                RollBack(_se);
            }
            catch (Exception)
            {
                State = TaskState.Error;
                throw;
            }
            State = TaskState.Success;
        }

        protected abstract void RollBack(ServiceEntityEx se);
        protected abstract void Execute(ServiceEntityEx se);

        public int Order { get; private set; }


    }
}